﻿#include "C3fdMonitorDatFileReader.h"
#include <QFile>
#include <QTextStream>

namespace MainWidget
{
	C3fdMonitorDatFileReader::C3fdMonitorDatFileReader(QString fileName)
	{
		parse(fileName);
	}

	int C3fdMonitorDatFileReader::getNumOfColumn() const
	{
		return m_Titles.size();
	}

	QStringList C3fdMonitorDatFileReader::getTitles() const
	{
		return m_Titles;
	}

	QList<QVector<double>> C3fdMonitorDatFileReader::getValues() const
	{
		return m_Values;
	}

	void C3fdMonitorDatFileReader::parse(QString fileName)
	{
		QFile datFile(fileName);
		if (datFile.open(QIODevice::ReadOnly | QIODevice::Text))
		{
			QTextStream dat(&datFile);
			QString line = dat.readLine().simplified();
			m_Titles = line.split(" ");
			while (true)
			{
				if (line.isNull()) {
					break;
				}
				line = dat.readLine().simplified();
				if (line.isEmpty()) {
					continue;
				}
				auto vals = parseStringtoDouble(line, m_Titles.size());
				if (vals.empty())
				{
					break;
				}
				else
				{
					m_Values.push_back(vals);
				}
			}
			datFile.close();
		}
	}

	QVector<double> C3fdMonitorDatFileReader::parseStringtoDouble(QString str, int count)
	{
		QVector<double> result = {};
		auto items = str.split(" ");
		if (items.size() != count)
		{
			return result;
		}
		bool ok;
		double val;
		for (auto s : items)
		{
			val = s.toDouble(&ok);
			if (ok)
			{
				result.push_back(val);
			}
			else
			{
				break;
			}
		}
		if (result.size() != count)
		{
			result.clear();
		}
		return result;
	}

}